package com.servlet.useraction;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.database.connection.DatabaseConnection;

@WebServlet("/UserRegister")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public RegisterServlet() { 	
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Get parameters from user submit.
		String userName = request.getParameter("txtUserName");
		String password = request.getParameter("txtPassword");
		String confirm  = request.getParameter("txtConfirm");
		java.util.Date utilDate = new java.util.Date();
		Date date = new Date(utilDate.getTime());

		response.getWriter().println(date);
		// Prepare SQL statements.
		String querySQL = "select * from user where UserName = ?";
		String addSQL = "insert into user values('" + userName + "', '" + 
							password + "', 'user', '" + date + "')";
		
		// Prepare connection to the database.
		Connection conn = null;			
		PreparedStatement stmt = null;
		ResultSet resultSet = null;
		if (confirm.equals(password)) {
			try {
				conn = DatabaseConnection.getConnection();			
				stmt = conn.prepareStatement(querySQL);
				stmt.setString(1, userName);
				resultSet = stmt.executeQuery();			
				// Account existed.
				if (resultSet.next()) {
					request.setAttribute("message", "Account existed!");
					request.getRequestDispatcher("RegisterForm.jsp").forward(request, response);
				}
				// Add new user to the database.
				stmt = conn.prepareStatement(addSQL);
				stmt.executeUpdate(addSQL);
				// Save the newly registered user to session.
				request.getSession().setAttribute("userName", userName);
				request.getSession().setAttribute("password", password);
				request.setAttribute("message", "Congratulations! You successfully registered!");
				request.getRequestDispatcher("RegisterSuccess.jsp").forward(request, response);
				
				resultSet.close();
				stmt.close();
				conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			}
		} else {
			request.setAttribute("message", "Password mismatch. Try again.");
			request.getRequestDispatcher("RegisterForm.jsp").forward(request, response);
		}
	}
}
